<template>
  <div class="lottery">
    <div class="lottery-box">
      <img class="lottery-bg" :src="images.lb_zhuanp_bg_0" v-show="toggleBg" alt="">
      <img class="lottery-bg" :src="images.lb_zhuanp_bg_1" v-show="!toggleBg" alt="">
      <ul ref="lotteryRef">
        <img class="lottery-bg" :src="images.lb_zhuanp_bg_0" v-show="toggleBg" alt="">
        <img class="lottery-bg" :src="images.lb_zhuanp_bg_1" v-show="!toggleBg" alt="">
        <li :class="`lottery-li-${index} li${item.sort+item.winOdds}`" v-for="(item, index) in activity.conData" :key="item.id">
          <span><img v-if="getWalletIcon(item.giftType)" :src="getWalletIcon(item.giftType)" alt="">{{ item.giftContent }}</span>
        </li>
      </ul>
      <img class="lottery-zhuan" :src="images.lb_btn_zhuanp" alt="">
      <img class="lottery-zhuanzi" @click="handleLottery" :src="images.lb_btn_zhuanp_zi" alt="">
      <img class="lottery-point" :src="images.lb_zhuanp_point" alt="">
    </div>
  </div>
  <Dialog
    v-model:visible="dialogConfig.show"
    v-model:title="dialogConfig.title"
    :width="dialogConfig.width"
    v-model:autoHeight="dialogConfig.autoHeight"
    v-model:hiddenTitle="dialogConfig.hiddenTitle"
    :headerFixed="dialogConfig.headerFixed"
    class="congratulations-dialog"
  >
    <div class="congratulations">
      <img :src="images.rewardbg" alt="">
      <h3><img :src="getWalletIcon(resultLottery.giftType)" alt=""> + {{ resultLottery.giftContent }}</h3>
      <h4 v-if="lotteryUser.num > 0" @click="handleLottery">{{ t("lotteryRecord.openAgain") }}</h4>
    </div>
  </Dialog>
</template>

<script setup lang="ts" name="Lottery">
import system from '@/store/system';
import userinfo from '@/store/userinfo';
import lotteryApi from '@/api/modules/lottery';
import nocache from '@/store/nocache';

const images: any = reactive({
  lb_btn_zhuanp: new URL(`../../assets/images/lottery/lb_btn_zhuanp.png`, import.meta.url).href,
  lb_btn_zhuanp_zi: new URL(`../../assets/images/lottery/lb_btn_zhuanp_zi.png`, import.meta.url).href,
  lb_zhuanp_bg_0: new URL(`../../assets/images/lottery/lb_zhuanp_bg_0.png`, import.meta.url).href,
  lb_zhuanp_bg_1: new URL(`../../assets/images/lottery/lb_zhuanp_bg_1.png`, import.meta.url).href,
  lb_zhuanp_point: new URL(`../../assets/images/lottery/lb_zhuanp_point.png`, import.meta.url).href,
  rewardbg: new URL(`../../assets/images/lottery/rewardbg.png`, import.meta.url).href,
});

const global:any = getCurrentInstance()?.appContext.config.globalProperties;
const piniaSystem:any = system();
const piniaUserinfo:any = userinfo();
const piniaNocache:any = nocache();
const emits = defineEmits(['queryData']);
const { t } = useI18n();


const data: any = reactive({
  toggleBg: true,
  toggleBgTimer: null,
  lotteryData: [],
  activity: {},
  listContent: [],
  listPic: [],
  listTitle: [],
  lotteryUser: {},
  resultLottery: {}, // 抽奖结果
  lotteryRef: null,
  lotteryStatus: false, // 抽奖状态
  navs: [],
  dialogConfig: {
    show: false,
    type: '',
    title: "",
    headerFixed: true,
    hiddenTitle: false,
    width: piniaSystem.getIsH5 ? '80%' : 400,
    autoHeight: true
  },
});

const {
  toggleBg,
  toggleBgTimer,
  lotteryData,
  activity,
  listContent,
  listPic,
  listTitle,
  lotteryUser,
  resultLottery,
  lotteryRef,
  lotteryStatus,
  navs,
  dialogConfig,
} = toRefs(data);


watch(
  () => piniaNocache.getLotteryActive,
  (val, preVal) => {
    initData();
  },
  { immediate: false, deep: true },
);


const getLotteryActivity = () => {
  lotteryApi.getLotteryActivity({}).then((response: any) => {
    if(response.code === 200){
      lotteryData.value = response.data;
      // 初始化一下值
      initData();
    }
  })
}
getLotteryActivity();

const initData = () => {
  activity.value = lotteryData.value[piniaNocache.getLotteryActive].activity || {};
  listContent.value = lotteryData.value[piniaNocache.getLotteryActive].listContent || [];
  listPic.value = lotteryData.value[piniaNocache.getLotteryActive].listPic || [];
  listTitle.value = lotteryData.value[piniaNocache.getLotteryActive].listTitle || [];
  lotteryUser.value = lotteryData.value[piniaNocache.getLotteryActive].lotteryUser || {};
  const currentCotent = activity.value.listContent.find((im:any)=>im.languageCode == piniaSystem.getLang.code);
  activity.value.content = currentCotent ? currentCotent.activityContent : "";
  piniaNocache.setActivity(activity.value);
  // 设置nav
  navs.value = lotteryData.value.map((element:any, index: number) => {
    const activity = element.activity;
    const currentTitle = activity.listName.find((im:any)=>im.languageCode == piniaSystem.getLang.code);
    if(currentTitle){
      return {
        label: currentTitle.content,
        active: index,
      }
    }else{
      return {
        label: activity.lotteryName,
        active: index,
      }
    }
  });
  emits('queryData', {
    activity: activity.value,
    listContent: listContent.value,
    listPic: listPic.value,
    listTitle: listTitle.value,
    lotteryUser: lotteryUser.value,
    navs: navs.value
  });
}

const addJoinLottery = () => {
  if(!lotteryStatus.value){
    lotteryApi.addJoinLottery({
      lotteryId: lotteryUser.value.lotteryId
    }).then((response: any)=>{
      if(response.code === 200){
        resultLottery.value = response.data;
        getLotteryActivity();
        // 得到结果 =》 开始转
        drawLotteryRaffle();
        global.message("close")
      }
    })
  }
}

// 获取rotate值函数
const getRotate = (ele: Element | null) => {
  if(ele){
    let values = window.getComputedStyle(ele, null).transform.split('(')[1].split(')')[0].split(',');
    let a: any = values[0];
    let b: any = values[1];
    let c: any = values[2];
    let d: any = values[3];
    let scale = Math.sqrt(a * a + b * b);
    let sin = b / scale;
    let angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));
    return angle;
  }else{
    return 0;
  }
}

const drawLotteryRaffle = () => {
  if(!lotteryStatus.value){
    lotteryStatus.value = true;
    const result = activity.value.conData.filter((item:any)=>item.sort == resultLottery.value.sort);
    const last = result[Math.floor(Math.random()*result.length)];
    const angle:any = 450 - getRotate(document.querySelector(`.li${last.sort+last.winOdds}`)) + 180 * 2;
    let start = 0;
    console.log("旋转度数：：：：：：：：：：：", angle)
    const animateRotate = () => {
      if(start < angle){
        start += 10;
        lotteryRef.value.style = `transform: rotateZ(${start}deg);`
      }else{
        // 抽奖结束
        clearInterval(interval);
        dialogConfig.value.show = true;
        lotteryStatus.value = false;
      }
    }
    // requestAnimationFrame(animateRotate);
    const interval = setInterval(animateRotate, 0)
  }
}

const handleLottery = () => {
  dialogConfig.value.show = false;
  // 抽奖
  addJoinLottery();
}


const getWalletIcon = (type: string) => {
  const icon = piniaUserinfo.getWallet.find((im:any)=>im.currencyId == type);
  return icon ? icon.currencyIcon : "";
}

const anmiteBg = () => {
  toggleBgTimer.value = setInterval(()=>{
    toggleBg.value = !toggleBg.value;
  }, 1000)
}
anmiteBg();

onUnmounted(()=>{
  clearInterval(toggleBgTimer.value);
})

</script>

<style lang="scss" scoped>
@import url('./index.scss');
.lottery-box{
  li{
    @for $i from 0 through 11{
      &.lottery-li-#{$i}{
        transform: rotateZ(#{$i * -30 + 90} + 'deg');
      }
    }
    span{
      display: flex;
      width: 45%;
      justify-content: center;
      align-items: center;
      color: #fff;
      position: relative;
      img{
        width: var(--rem-20);
        height: var(--rem-20);
        margin-right: var(--rem-5);
      }
    }
  }
}
.congratulations{
  position: relative;
  h3{
    position: absolute;
    bottom: var(--rem-70);
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: var(--rem-10);
    color: white;
    font-weight: 700;
    font-size: var(--rem-30);
    img{
      margin-right: var(--rem-10);
    }
  }
  h4{
    position: absolute;
    bottom: var(--rem-10);
    border-radius: var(--rem-50);
    cursor: pointer;
    margin: var(--rem-10) auto;
    width: var(--rem-200);
    height: var(--rem-50);
    left: 50%;
    margin-left: var(--rem-100-n);
    text-align: center;
    line-height: var(--rem-50);
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--z-bg-btn);
    color: white;
  }
}
</style>
